package admin

import (
	"gin_demo/internal/consts"
	"gin_demo/internal/model"
	"gin_demo/utility"
	"time"

	"github.com/gin-gonic/gin"
)

func Create(ctx *gin.Context, req AdminReq) {
	pwd, ok := utility.BctypMake([]byte(req.PassWord))
	if !ok {

		utility.Fail(ctx, "用户添加失败")
	} else {
		list := model.AdminInfo{
			UserName: req.UserName,
			Password: pwd,
			IsAdmin:  req.IsAdmin,
			RoleIds:  req.RoleIds,
		}
		tx := consts.App.DB.Create(&list)
		if tx.Error != nil {
			utility.Fail(ctx, "用户添加失败")
		} else {
			res := AdminRest{
				Id:        list.ID,
				UserName:  list.UserName,
				RoleIds:   list.RoleIds,
				CreatedAt: list.Tiestamps.CreateAt,
				UpdatedAt: list.Tiestamps.UpdateAt,
				IsAdmin:   list.IsAdmin,
			}
			utility.Success(ctx, res)
		}
	}
}

func List(ctx *gin.Context) {
	list := []model.AdminInfo{}
	tx := consts.App.DB.Find(&list)
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())

		utility.Fail(ctx, "用户数据加载失败")
	} else {
		utility.Success(ctx, list)
	}
}

func Delete(ctx *gin.Context, req SoftDeleteReq) {
	tx := consts.App.DB.Model(&model.AdminInfo{}).Where("id=?", req.Id).Update("deleted_at", time.Now())
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "删除失败")
	} else {
		utility.Success(ctx, "删除成功")
	}
}

func Update(ctx *gin.Context, req UpdateMyPasswordReq) {
	pwd, _ := utility.BctypMake([]byte(req.Password))
	tx := consts.App.DB.Model(&model.AdminInfo{}).Where("id=?", req.Id).Update("password", pwd)
	if tx.Error != nil {
		consts.App.Log.Error(tx.Error.Error())
		utility.Fail(ctx, "密码修改失败")
	} else {
		utility.Success(ctx, "密码修改成功")
	}
}
